package pl.edu.mimuw.irs.core.model.petrinet;

import java.util.HashSet;
import java.util.Set;

import pl.edu.mimuw.irs.core.global.IDManager;
import pl.edu.mimuw.irs.core.util.Position;

/**
 * @author Jakub Rauch
 * Created on: 2009-05-07
 */
public class Transition extends Node implements ITransition {

	private static final long serialVersionUID = -1961687975821994307L;
	
	// *** Attributes

	// Getters and setters
	
	// *** Constructors

	public Transition(IDManager idManager, String id, Position position) {
		super(idManager);
		if (id == null) id = idManager.getNewId();
		setId(id);
		setPosition(position);
	}

	public Transition(IDManager idManager, Position position) {
		this(idManager, null, position);
	}

	public Transition(IDManager idManager, String id) {
		this(idManager, id, new Position());
	}

	public Transition(IDManager idManager) {
		this(idManager, (String)null);
	}
	
	/*
	 * Should be used only for deserialization.
	 */
	public Transition() {
		
	}

	/** Copying constructor. */
	public Transition(Transition transition) {
		super(transition);
	}
	
	// *** Methods
	
	public boolean isActive() {
		for (Arc arc : getIncomingArcs()) {
			if (!arc.isActive()) return false;
		}
		return true;
	}
	
	public boolean invoke() {
		for (Arc incomingArc : getIncomingArcs()) {
			incomingArc.invoke();
		}
		for (Arc outgoingArc : getOutgoingArcs()) {
			outgoingArc.invoke();
		}
		return true;
	}
	
	public Set<ITransition> getFollowingActiveTransitions() {
		Set<ITransition> suspectTransitions = new HashSet<ITransition>();
		Set<ITransition> activatedTransitions = new HashSet<ITransition>();

		for (Arc arcTP : getOutgoingArcs()) {
			for (Arc arcPT : arcTP.getPlace().getOutgoingArcs()) {
				suspectTransitions.add(arcPT.getTransition());
			}
		}
		
		for (ITransition suspectTransition : suspectTransitions) {
			if (suspectTransition.isActive()) {
				activatedTransitions.add(suspectTransition);
			}
		}
		
		return activatedTransitions;
	}
	
	/** 
	 * Simply returns the instance using copying constructor for this object - {@link #Transition(Transition)}.
	 */
	@Override
	public Transition clone() {
		return new Transition(this);
	}
}
